<?php

namespace app\merchant\controller;

use app\admin\model\Goods as ModelGoods;
use app\admin\model\GoodsComment;
use app\admin\model\Order as ModelOrder;
use app\admin\model\StoreOrderStatus;
use app\admin\model\UserMerchant;
use think\facade\View;
use app\common\services\RedisService;
use app\common\Tools;
use app\Request;

class Order extends Base 
{
    //订单列表
    public function list(Request $request){
        return View::fetch();
    }

    //订单评价
    public function review(Request $request){
        return View::fetch();
    }
    

    //获取订单列表
    public function get_order_list(Request $request){
        $post_data = $request->getMore([
            ['page', 1],
            ['limit', 10],
            ['keyword', ''],
            ['goods_type',''],
            ['status','']
        ]);
        $query = ModelOrder::search_model($post_data)->append(['status_text'])->where('merchant_id',0)
        ->when($post_data['keyword'], function ($query) use ($post_data) {
            $query->where('order_id|real_name|user_phone|goods_name', 'like', '%' . $post_data['keyword'] . '%');
        })
        ->when($post_data['status'] !== '', function ($query) use ($post_data) {
            $query->where('status', $post_data['status']);
        })
        ->when(!empty($post_data['goods_type']), function ($query) use ($post_data) {
            $query->where('goods_type', $post_data['goods_type']);
        });
        $count = $query->count();
        $list = $query->page($post_data['page'], $post_data['limit'])->order('id desc')->select()->toArray();

        return app('json')->layuiTableResponse('ok',$list,$count);
    }


        //获取订单评价
    public function get_order_review(Request $request){
            $post_data = $request->getMore([
                ['page', 1],
                ['limit', 10],
                ['keyword', ''],
                ['goods_type',''],
                ['status','']
            ]);
            $query = GoodsComment::with(['user','goods','order'])
            ->when($post_data['keyword'], function ($query) use ($post_data) {
                $query->where('order_id|real_name|user_phone|goods_name', 'like', '%' . $post_data['keyword'] . '%');
            })
            ->when($post_data['status'] !== '', function ($query) use ($post_data) {
                $query->where('status', $post_data['status']);
            })
            ->when(!empty($post_data['goods_type']), function ($query) use ($post_data) {
                $query->where('goods_type', $post_data['goods_type']);
            });
            $count = $query->count();
            $list = $query->page($post_data['page'], $post_data['limit'])->order('id desc')->select()->toArray();
    
            return app('json')->layuiTableResponse('ok',$list,$count);
        }


      //获取退款订单列表
      public function get_refund_list(Request $request){
        $post_data = $request->getMore([
            ['page', 1],
            ['limit', 10],
            ['keyword', ''],
            ['goods_type',''],
            ['refund_status','']
        ]);
        $query = ModelOrder::search_model($post_data)->append(['status_text'])->where('merchant_id',0)->where('refund_status','>',0)
        ->when($post_data['keyword'], function ($query) use ($post_data) {
            $query->where('order_id|real_name|user_phone|goods_name', 'like', '%' . $post_data['keyword'] . '%');
        })
        ->when($post_data['refund_status'] != '', function ($query) use ($post_data) {

            if($post_data['refund_status'] == 1){
                // 退款
                $query->where('status', 4)->where('refund_express','NULL');
            }
            if($post_data['refund_status'] == 2){
                // 退货退款
                $query->where('status', 4)->where('refund_express','NOT NULL');
            }
            if($post_data['refund_status'] == 3){
                // 同意退款
                $query->where('status', 5);
            }
            if($post_data['refund_status'] == 4){
                // 拒绝退款
                $query->where('status', 6);
            }
        })
        ->when(!empty($post_data['goods_type']), function ($query) use ($post_data) {
            $query->where('goods_type', $post_data['goods_type']);
        });
        $count = $query->count();
        $list = $query->page($post_data['page'], $post_data['limit'])->order('id desc')->select()->toArray();

        return app('json')->layuiTableResponse('ok',$list,$count);
    }

    /**
     * 订单详情
     *
     * @return void
     */
    public function details(){
        $order_id = request()->get('id','');
        if(!$order_id) exception('参数错误');
        $order = ModelOrder::where('order_id',$order_id)->with(['cartDetail','user'])->append(['status_name'])->find();
        if(!$order) exception('订单不存在');
        view::assign('order',$order);
        return View::fetch();
    }

    


       /**
     * 订单详情
     *
     * @return void
     */
    public function refund_detail(){
        $order_id = request()->get('id','');
        if(!$order_id) exception('参数错误');
        $order = ModelOrder::where('order_id',$order_id)->with(['cartDetail','user'])->append(['status_name'])->find();
        if(!$order) exception('订单不存在');
        view::assign('order',$order);
        return View::fetch();
    }

    

        /**
     * 订单退款页
     *
     * @return void
     */
    public function shop_back(){
        return View::fetch();
    }

    


        /**
     * 订单备注
     *
     * @param Request $request
     * @return void
     */
    public function remark(Request $request){
        $redis_service = RedisService::getInstance();
       $lock_key = "api:order_remark:" . $this->uid;

       try {
           $action_lock = $redis_service->acquireLock($lock_key, 3); // 原子设置+过期时间
           if (!$action_lock) {
               exception('请勿重复提交');
           }

           $post_data = $request->postMore([
               ['order_id', ''],
               ['remark', ''],
           ]);

           Tools::check($post_data, [
               'order_id' => 'require',
               'remark' => 'require',
           ], [
               'order_id.require' => '订单号不得为空',
               'remark.require' => '备注不得为空',
           ]);

           $exists = ModelOrder::where('order_id', $post_data['order_id'])->find();
           if(!$exists) {
               exception('订单不存在');
           }
           
           $exists->merchant_remark  = $post_data['remark'];
           $exists->save();
           StoreOrderStatus::setStatus($exists->id, 'delivery_remark', '商家订单备注：' . $post_data['remark']);
       } catch (\Exception $e) {
           return app('json')->fail($e->getMessage());

       } finally {
           // 🧹 无论成功与否，释放锁
           $redis_service->releaseLock($lock_key);
       }

       return app('json')->success('提交成功，等待审核');
}

    /**
     * 发货
     *
     * @param Request $request
     * @return void
     */
    public function deliver(Request $request){
             $redis_service = RedisService::getInstance();
            $lock_key = "api:order_deliver:" . $this->uid;

            try {
                $action_lock = $redis_service->acquireLock($lock_key, 3); // 原子设置+过期时间
                if (!$action_lock) {
                    exception('请勿重复提交');
                }

                $post_data = $request->postMore([
                    ['order_id', ''],
                    ['express_no', ''],
                    ['express_name', '']
                ]);

                Tools::check($post_data, [
                    'order_id' => 'require',
                    'express_no' => 'require',
                ], [
                    'order_id.require' => '订单号不得为空',
                    'express_no.require' => '快递单不得为空',
                ]);

                $exists = ModelOrder::where('order_id', $post_data['order_id'])->find();
                if(!$exists) {
                    exception('订单不存在');
                }
                
                if ($exists && $exists['status'] != 1) {
                    exception('订单状态异常');
                }
                if($exists->paid == 0) {
                    exception('订单未支付');
                }
                $exists->status = 2; // 发货状态
                $exists->delivery_id = $post_data['express_no']; // 快递单号
                $exists->delivery_name = $post_data['express_name']; // 快递单号
                $exists->deliver_time  = date('Y-m-d H:i:s');
                $exists->save();
                StoreOrderStatus::setStatus($exists->id, 'delivery_goods', '已发货 快递公司：' . $post_data['express_name'] . ' 快递单号：' . $post_data['express_no']);
            } catch (\Exception $e) {
                return app('json')->fail($e->getMessage());

            } finally {
                // 🧹 无论成功与否，释放锁
                $redis_service->releaseLock($lock_key);
            }

            return app('json')->success('提交成功，等待审核');
    }


     /**
     * 退款
     *
     * @param Request $request
     * @return void
     */
    public function refund(Request $request){
        $redis_service = RedisService::getInstance();
        $lock_key = "api:order_refund:" . $this->uid;

        try {
            $action_lock = $redis_service->acquireLock($lock_key, 3); // 原子设置+过期时间
            if (!$action_lock) {
                exception('请勿重复提交');
            }

            $post_data = $request->postMore([
                ['order_id', ''],
                ['refund_amount', ''],
                ['refund_reason', '']
            ]);

            Tools::check($post_data, [
                'order_id' => 'require',
                'refund_amount' => 'require',
            ], [
                'order_id.require' => '订单号不得为空',
                'refund_amount.require' => '退款金额不得为空',
            ]);

            $exists = ModelOrder::where('order_id', $post_data['order_id'])->where('merchant_id',$this->uid)->find();
            if(!$exists) {
                exception('订单不存在');
            }
            if($exists->paid == 0) {
                    exception('订单未支付');
                }
            if ($exists && $exists['status'] != 1) {
                exception('订单状态异常');
            }
            
            if($exists->refund_status !=1) exception('订单状态异常');
                $bj = bccomp((float)$exists['pay_price'], (float)$exists['refund_price'], 2);
                if ($bj < 0) exception('退款金额大于支付金额，请修改退款金额');
                $data['status'] = 5;
                $service = new \app\common\api\WeChat;
                $refund_order_sn = 'TK'.time(); //退款单号  自行生成
                $res = $service->doRefund($exists->pay_price,$data['refund_price'],$refund_order_sn,$exists->transaction_id);
                $data['refund_sn']   = $refund_order_sn;
                ModelOrder::update($data,['id'=>$exists->id]);
                $merchant = UserMerchant::where('id',$this->uid)->find();
                $merchant->balance -= $data['refund_price'];
                $merchant->total_balance -= $data['refund_price'];
                $merchant->save();
                StoreOrderStatus::setStatus($exists->id, 'refund_price', '退款给用户' . $data['refund_price'] . '元');
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage());

        } finally {
            // 🧹 无论成功与否，释放锁
            $redis_service->releaseLock($lock_key);
        }

        return app('json')->success('操作成功');
    }

    //评价删除
    public function review_delete(Request $request){
        $redis_service = RedisService::getInstance();
        $lock_key = "api:order_review_delte:" . $this->uid;

        try {
            $action_lock = $redis_service->acquireLock($lock_key, 3); // 原子设置+过期时间
            if (!$action_lock) {
                exception('请勿重复提交');
            }

            $post_data = $request->postMore([
                ['id', ''],
            ]);

            Tools::check($post_data, [
                'id' => 'require',
            ], [
                'id.require' => 'ID不得为空',
            ]);

            $exists = GoodsComment::where('id', $post_data['id'])->find();
            if(!$exists) {
                exception('评级记录不存在');
            }
           $exists->delete();
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage());

        } finally {
            // 🧹 无论成功与否，释放锁
            $redis_service->releaseLock($lock_key);
        }

        return app('json')->success('操作成功');
    }
}
